package study.io.springboot.upload.service;

import cn.hutool.core.util.RandomUtil;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import study.io.springboot.upload.support.utils.CopyUtils;
import study.io.springboot.upload.support.utils.URLUtils;

import java.net.URL;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ParallelCopyService {

    private ExecutorService pool = Executors.newFixedThreadPool(10);

    public void copyV1(List<String> srcLt, String dest) {
        Stopwatch stopwatch = Stopwatch.createStarted();

        List<URL> urlLt = URLUtils.toURLs(srcLt);
        urlLt.parallelStream().forEach(e -> {
            Stopwatch s = Stopwatch.createStarted();
            CopyUtils.copyURLToFile(e, dest + RandomUtil.randomInt() + ".pdf");
            log.info(">>>>>>>>>> {} sec", s.elapsed(TimeUnit.SECONDS));
        });
        log.info("total cost time: {} sec", stopwatch.elapsed(TimeUnit.SECONDS));
    }

    public void copyV2(List<String> urlLt, String dest) {
        Stopwatch stopwatch = Stopwatch.createStarted();

        List<URL> myUrlLt = URLUtils.toURLs(urlLt);
        CountDownLatch latch = new CountDownLatch(myUrlLt.size());
        for (URL url : myUrlLt) {
            pool.execute(() -> {
                Stopwatch task = Stopwatch.createStarted();
                CopyUtils.copyURLToFile(url, dest + RandomUtil.randomInt() + ".pdf");
                log.info(">>>>>>>>>> {} sec", task.elapsed(TimeUnit.SECONDS));
                latch.countDown();
            });
        }
        try {
            latch.await();
        } catch (Exception ex) {
        }

        log.info("total cost time: {} sec", stopwatch.elapsed(TimeUnit.SECONDS));
    }
}
